import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/model/AppUserDetail.dart';
import 'package:easy_chat_app/commons/utils/RouteUtils.dart';
import 'package:easy_chat_app/commons/utils/UserHeadPortraitUtils.dart';
import 'package:easy_chat_app/commons/widget/UserHeadPortrait.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

class MobileUserHeadPortraitPageChangeNotifier with ChangeNotifier {
  final Logger logger = Logger();

  MobileUserHeadPortraitPageChangeNotifier();
}

// class MobileUserHeadPortraitPage extends StatefulWidget {
//   const MobileUserHeadPortraitPage({super.key});
//
//   @override
//   State<StatefulWidget> createState() {
//     return _MobileUserHeadPortraitPage();
//   }
// }

class MobileUserHeadPortraitPage extends StatelessWidget {
  Logger logger = Logger();

  MobileUserHeadPortraitPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (context) {
            return MobileUserHeadPortraitPageChangeNotifier();
          })
        ],
        child: Consumer<AppUserDetailChangeNotifier>(
            builder: (context, appUserDetailChangeNotifier, child) {
          AppUserDetail appUserDetail =
              appUserDetailChangeNotifier.getAppUserDetail();
          return Scaffold(
            backgroundColor: Colors.black,
            appBar: AppBar(
              title: const Text(
                "头像",
                style: TextStyle(color: Colors.white),
              ),
              centerTitle: true,
              backgroundColor: Colors.black,
              leading: const BackButton(
                color: Colors.white,
              ),
              actions: [
                IconButton(
                    onPressed: () {
                      showModalBottomSheet(
                          context: context,
                          backgroundColor: Colors.white,
                          builder: (_) {
                            return SizedBox(
                              width: double.infinity,
                              height: 250,
                              child: Column(
                                children: [
                                  Container(
                                    decoration: const BoxDecoration(
                                        border: Border(
                                            bottom: BorderSide(
                                                color: Color.fromRGBO(
                                                    247, 247, 247, 1)))),
                                    height: 50,
                                    width: double.infinity,
                                    child: TextButton(
                                        onPressed: () async {
                                          XFile? xFile = await ImagePicker()
                                              .pickImage(
                                                  source: ImageSource.camera);
                                          if (xFile != null) {
                                            await RouteUtils
                                                .route2MobileUserHeadPortraitPreviewPage(
                                                    appUserDetail, xFile);
                                            RouteUtils.pop();
                                            await appUserDetailChangeNotifier
                                                .reload();
                                          }
                                        },
                                        child: const Text(
                                          "拍照",
                                          style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 18),
                                        )),
                                  ),
                                  Container(
                                    decoration: const BoxDecoration(
                                        border: Border(
                                            bottom: BorderSide(
                                                color: Color.fromRGBO(
                                                    247, 247, 247, 1),
                                                width: 1))),
                                    width: double.infinity,
                                    height: 50,
                                    child: TextButton(
                                        onPressed: () async {
                                          logger.i("从相册选择");
                                          XFile? xFile = await ImagePicker()
                                              .pickImage(
                                                  source: ImageSource.gallery);
                                          if (xFile != null) {
                                            await RouteUtils
                                                .route2MobileUserHeadPortraitPreviewPage(
                                                    appUserDetail, xFile);
                                            RouteUtils.pop();
                                            await appUserDetailChangeNotifier
                                                .reload();
                                          }
                                        },
                                        child: const Text(
                                          "从相册选择",
                                          style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 18),
                                        )),
                                  ),
                                  Container(
                                    decoration: const BoxDecoration(
                                        border: Border(
                                            bottom: BorderSide(
                                                width: 10,
                                                color: Color.fromRGBO(
                                                    247, 247, 247, 1)))),
                                    width: double.infinity,
                                    height: 50,
                                    child: TextButton(
                                        onPressed: () async {
                                          downloadUserPortrait(appUserDetail);
                                          RouteUtils.pop();
                                        },
                                        child: const Text(
                                          "保存图片",
                                          style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 18),
                                        )),
                                  ),
                                  SizedBox(
                                    width: double.infinity,
                                    height: 50,
                                    child: TextButton(
                                        onPressed: () {
                                          Navigator.pop(context);
                                        },
                                        child: const Text(
                                          "取消",
                                          style: TextStyle(
                                              color: Colors.black,
                                              fontSize: 18),
                                        )),
                                  )
                                ],
                              ),
                            );
                          });
                    },
                    icon: const Icon(
                      Icons.more_horiz,
                      color: Colors.white,
                    ))
              ],
            ),
            body: Container(
              alignment: Alignment.center,
              child: Image.network(
                  UserHeadPortraitUtils.buildUserHeadPortrait(appUserDetail)!),
            ),
          );
        }));
  }

  Future<void> downloadUserPortrait(AppUserDetail userDetail) async {
    var response = await Dio().get(
        UserHeadPortrait.buildUserHeadPortraitURL(
            userCode: userDetail.code!,
            userHeadPortrait: userDetail.headPortrait!,
            userHeadPortraitStoreType: userDetail.headPortraitStoreType!),
        options: Options(responseType: ResponseType.bytes));
    String fileName = DateTime.now().millisecondsSinceEpoch.toString();
    await ImageGallerySaver.saveImage(Uint8List.fromList(response.data),
        quality: 60, name: fileName);
    await Fluttertoast.showToast(
        msg: "图片保存成功", toastLength: Toast.LENGTH_SHORT);
  }
}
